import re
import random
from django import forms
from django_redis import get_redis_connection
from django.conf import settings
from django.core.validators import RegexValidator
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from django.core.exceptions import ValidationError

from app01 import models
from utils.ihuyi import sms


def send_sms(request):
    """发送短信：用POST,不想在url中暴露手机号
    腾讯云短信服务登录和注册短息的模板不一样
    ?tpl=login ---> 548762
    ?tpl=register ---> 548760
    """
    # tpl = request.GET.get('tpl')
    # tpl_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    # if not tpl_id:
    #     return HttpResponse('模板不存在')
    # code = random.randrange(1000, 9999)
    # message = sms.send_sms_single('15257572396', code)
    # return HttpResponse(message.encode('utf-8'))
    if request.method == 'POST':
        res = {
            'msg': None
        }
        mobile_phone = request.POST.get('mobile_phone')
        if not mobile_phone:
            res['msg'] = '请输入手机号'
        else:
            ret = re.match(r"1[3456789]\d{9}", mobile_phone)
            if not ret:
                res['msg'] = '手机号格式不对'
            else:
                tpl = request.POST.get('tpl')
                tpl_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
                if not tpl_id:
                    res['msg'] = '模板不存在'
                else:
                    code = random.randrange(1000, 9999)
                    print(111, code)
                    # 短信sms
                    # message = sms.send_sms_single(mobile_phone, code)
                    conn = get_redis_connection('default')
                    conn.set(mobile_phone, code, ex=60)
                    conn.close()
                    # print(conn.get(mobile_phone).decode('utf-8'))
        return JsonResponse(res)


class RegisterModelForm(forms.ModelForm):
    mobile_phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^1[3|4|5|6|7|8|9]\d{9}$', '手机号格式错误'), ])
    password = forms.CharField(label='密码', widget=forms.PasswordInput(), error_messages={})

    confirm_password = forms.CharField(label='确认密码', widget=forms.PasswordInput())
    code = forms.CharField(label='验证码')

    class Meta:
        model = models.UserInfo
        fields = ['username', 'email', 'password', 'confirm_password', 'mobile_phone', 'code']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            # print(name)  # 字段的名称，比如：username
            field.widget.attrs = {'class': 'form-control', 'placeholder': f'请输入{field.label}'}
            field.error_messages = {'required': '{}不能为空'.format(field.label), }

    def clean_username(self):
        val = self.cleaned_data.get('username')
        ret = models.UserInfo.objects.filter(username=val).first()
        if ret:
            raise ValidationError('用户已存在')
        return val

    def clean_code(self):
        code = self.cleaned_data.get('code')
        if not code:
            raise ValidationError('验证码不能为空')
        mobile_phone = self.cleaned_data.get('mobile_phone')
        conn = get_redis_connection('default')
        ret = conn.get(mobile_phone)
        if not ret:
            raise ValidationError('手机号不一致')
        if code != ret.decode('utf-8'):
            raise ValidationError('验证码不正确')
        conn.close()
        return code


    def clean(self):
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if password and confirm_password:
            if password == confirm_password:
                return self.cleaned_data
            else:
                raise ValidationError('两次密码不一致')
        else:
            return self.cleaned_data


def register(request):
    if request.method == 'POST':
        form = RegisterModelForm(request.POST)
        if form.is_valid():
            form.cleaned_data.pop('code')
            form.cleaned_data.pop('confirm_password')
            form.save()
            return JsonResponse({'a': 'b'})
        return render(request, 'app01/register.html', {'form': form})
    form = RegisterModelForm()
    return render(request, 'app01/register.html', {'form': form})


def demo(request):
    """  """
    return render(request, 'app01/demo.html')


def demo1(request):
    return render(request, 'app01/demo_1.html')


def bos_credential(request):
    # 生成一个临时凭证，并给前端返回
    from baidubce.services.bos.bos_client import BosClient
    from utils.baidu import sts_sample
    # 新建BosClient
    """
    bosConfig = {
        credentials: {
            ak: '{accessKeyId}', // STS服务器下发的临时ak
            sk: '{secretAccessKey}' // STS服务器下发的临时sk
        },
        sessionToken: '{sessionToken}', // STS服务器下发的sessionToken
        endpoint: 'http://bj.bcebos.com'
    }
    """
    res = {
        'status': True,
        'bosConfig': {
            'credentials': {
                'ak': sts_sample.sts_ak,
                'sk': sts_sample.sts_sk,
            },
            'sessionToken': sts_sample.token,
            'endpoint': 'https://fsh.bcebos.com',
        }
    }
    return JsonResponse(res)